package com.dt.export.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.dt.app.api.sys.service.SysExcelImportService;
import com.dt.export.config.CustomCellWriteHandlerConfig;
import com.dt.export.listener.ExcelDataListener;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

import static com.dt.export.config.CustomCellStyleConfig.customStyle;

/**
 * Excel导入导出工具类
 * @author DT
 * @date 2021/10/23 20:27
 */
public class ExcelUtils {

    /**
     * Excel导出
     * @param response  响应
     * @param excelName Excel名称
     * @param sheetName sheet页名称
     * @param clazz     Excel要转换的类型
     * @param data      要导出的数据
     * @param excludeColumnFiledNames 筛选列
     * @throws Exception 抛出异常
     */
    public static void exportExcel(HttpServletResponse response, String excelName, String sheetName, Class<?> clazz, List<?> data,List<String> excludeColumnFiledNames) throws Exception {
        // 设置响应类型
        response.setContentType("application/vnd.ms-excel");
        // 设置字符编码
        response.setCharacterEncoding("UTF-8");
        // 设置响应头信息
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(excelName,"UTF-8") + ".xlsx");
        // 写入文件
        EasyExcel.write(response.getOutputStream(), clazz)
                .needHead(true)
                .registerWriteHandler(new CustomCellWriteHandlerConfig())
                .registerWriteHandler(customStyle())
                // 筛选导出字段
                .includeColumnFiledNames(excludeColumnFiledNames)
                .sheet(sheetName)
                .doWrite(data);
    }

    /**
     * 从本地Excel导入
     * @param fileName 文件地址
     * @param clazz  Excel要转换的类型
     */
    public static void importExcel(String fileName, Class<?> clazz, SysExcelImportService sysExcelImportService) {
        // 一个文件一个reader
        ExcelReader excelReader = null;
        try {
            excelReader = EasyExcel.read(fileName, clazz, new ExcelDataListener(sysExcelImportService)).build();
            // 构建一个sheet
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            // 读取一个sheet
            excelReader.read(readSheet);
        } finally {
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }
    }

}
